package com.schpro.webexperiment.service.impl;

import com.schpro.webexperiment.model.BaseModel;
import com.schpro.webexperiment.model.Belong;
import com.schpro.webexperiment.model.Exercise;
import com.schpro.webexperiment.model.Experiment;
import com.schpro.webexperiment.model.Type;
import com.schpro.webexperiment.service.BelongService;
import com.schpro.webexperiment.service.CommonService;
import com.schpro.webexperiment.service.ExeService;
import com.schpro.webexperiment.service.ExpService;
import com.schpro.webexperiment.service.TypeService;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * exercise service impl
 *
 * @author lss
 * @date 2019-02-26, Tue
 */
@Service
public class CommonServiceImpl implements CommonService {

  @Autowired
  private BelongService belongService;

  @Autowired
  private TypeService typeService;

  @Autowired
  private ExpService expService;

  @Autowired
  private ExeService exeService;

  @Override
  public List<BaseModel> getTree() {

    List<Belong> belongs = belongService.getAllBelongs();
    if (CollectionUtils.isEmpty(belongs)) {
      return null;
    }
    List<Type> types = typeService.getAllBTypes();
    if (CollectionUtils.isEmpty(types)) {
      return null;
    }
    List<Experiment> exps = expService.getAllExps();
    if (CollectionUtils.isEmpty(exps)) {
      return null;
    }
    Map<String, Experiment> expMap = exps.stream()
        .collect(Collectors.toMap(Experiment::getId, v -> v));

    List<Exercise> exercises = exeService.getAllExercises();
    if (CollectionUtils.isEmpty(exercises)) {
      return null;
    }
    belongs.forEach(b ->
        b.setChildren(
            types.stream()
                .filter(v -> v.getRefId().equals(b.getId()))
                .collect(Collectors.toList())));
    types.forEach(
        t -> t.setChildren(
            exps.stream().filter(e -> e.getRefId().equals(t.getId()))
                .collect(Collectors.toList())));

    exercises.forEach(a -> {
      Experiment exp = expMap.get(a.getRefId());
      List<Exercise> children = exp.getChildren();
      if (CollectionUtils.isEmpty(children)) {
        exp.setChildren(new LinkedList<>());
      }
      exp.getChildren().add(a);
    });
    return new LinkedList<>(belongs);
  }
}
